import { Text, View } from '@tarojs/components';
import theme from '@/theme';
import { ComponentProps, useMemo, useState } from 'react';
import './index.scss';
import classNames from 'classnames';
import { Icon, Space } from 'pd-taro-ui';

interface CheckboxGroupProps {
  placeholder?: string;
  value?: string | string[];
  onChange?: (value: string | string[]) => void;
  onBlur?: any;
  staticed?: boolean;
  disabled?: boolean;
  compProps?: any;

  /** 是否拼接字符串，返回数组或字符串，默认true字符串 */
  joinValues?: boolean;
  /** 字符串拼接符号，默认, */
  delimiter?: string;
  /** 渲染标签：默认label */
  labelField?: string;
  /** 渲染值：默认value */
  valueField?: string;
  /** 是否显示为一行，默认true */
  inline?: boolean;
  options?: { label: any; value: any; [key: string]: any }[];
}
const CheckboxGroup = ({
  onChange,
  value,
  disabled,
  staticed,
  onBlur,
  placeholder,
  compProps,
  options = [],
  inline = true,
  joinValues = true,
  labelField = 'label',
  valueField = 'value',
  delimiter = ',',
}: CheckboxGroupProps) => {
  const checks = useMemo(() => {
    let list: string[] = [];
    if (value) {
      if (typeof value === 'string') {
        list = value.split(delimiter);
      } else if (Array.isArray(value)) {
        list = value;
      }
    }
    return list;
  }, [value, delimiter]);

  const setCheck = (item: any) => {
    if (disabled) {
      return;
    }
    const val = item[valueField];
    const _value = checks ? [...checks] : [];
    const index = _value.indexOf(val);
    if (~index) {
      _value.splice(index, 1);
    } else {
      _value.push(val);
    }
    onChange?.(joinValues ? _value.join(',') : _value);
  };
  const getIsCheck = (item: any) => {
    const val = item[valueField];
    return checks?.includes(val);
  };

  const staticStr = useMemo(() => {
    let str = '';
    let values: any[];
    if (value) {
      if (typeof value === 'string' || Array.isArray(value)) {
        if (typeof value === 'string') {
          values = value.split(delimiter);
        } else {
          values = value;
        }
        str = values
          .map(v => {
            return options.find(option => option[valueField] == v)?.[labelField] || ' ';
          })
          .join(delimiter);
      } else {
        str = JSON.stringify(value);
      }
    }
    // console.log('checkboxgroup staticStr', { values, value, str });
    return str;
  }, [value, delimiter, options, labelField, valueField]);

  if (staticed) {
    return <View className='pd-checkboxGroup--static'>{staticStr}</View>;
  }
  return (
    <View className={classNames({ 'pd-checkboxGroup': true, 'pd-checkboxGroup--disabled': disabled })}>
      <Space row={inline} items={inline ? 'center' : 'stretch'} wrap={true}>
        {options.map((item, index) => {
          const checked = getIsCheck(item);
          return (
            <Space key={index} row items='center' gap={8} onClick={() => setCheck(item)}>
              <Icon name={checked ? 'Checked' : 'Unchecked'} color={checked ? theme.primaryColor : '#bbb'} />
              {!!item[labelField] && <Text className='pd-checkboxGroup__label'>{item[labelField]}</Text>}
            </Space>
          );
        })}
      </Space>
    </View>
  );
};
export default CheckboxGroup;
